package com.rockcent.mall.controller;

import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.mall.Routes;
import com.rockcent.mall.helper.BannerHelper;
import com.rockcent.mall.lib.domain.Banner;
import com.rockcent.mall.lib.dto.BannerDto;
import com.rockcent.mall.lib.dto.UserInfoDto;
import com.rockcent.mall.lib.helper.BaseUserHelper;
import com.rockcent.mall.lib.repository.BannerRepository;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 包含功能：
 * 新增、修改、删除、查询信息、查询列表、排序
 * Created by zhangjh on 2016/11/11.
 */
@RestController
public class BannerController extends BaseController {

    private final Logger log = LoggerFactory.getLogger(BannerController.class);

    @Autowired
    private BaseUserHelper userHelper;


    @Autowired
    private BannerRepository bannerRepository;

    @Autowired
    private BannerHelper bannerHelper;

    /**
     * @api {get} /mall/mobile/banner/info 查询banner
     * @apiGroup mall_mobileBanner
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {String} id <code>必须参数</code> 记录id
     * @apiSuccessExample {json} Success-Response:
     * {
     *     "code":"1",
     *     "desc":"成功",
     *     "data":{
     *         "id":10,
     *         "dateCreated":"2016-06-13 18:28:41",
     *         "lastUpdated":"2016-11-11 19:08:18",
     *         "version":1,
     *         "mallId":1,
     *         "picPath":"/20161110/2016111018013002.png",
     *         "seqNo":1,
     *         "title":"testTitle04",
     *         "url":"www.sougou.com"
     *     }
     * }
     */
    @RequestMapping(value = Routes.MALL_MOBILE_BANNER, method = RequestMethod.GET)
    public JsonResult queryInfo(@RequestParam("id") Long id, HttpServletRequest request) {
        UserInfoDto userDto = userHelper.getSession(request);
        Long mallId = userDto.mall.getId();
        RestDoing doing = jsonResult -> {
            if (null == id) {
                jsonResult.errorParam("ID不能为空", log);
                return;
            }
            Banner banner = bannerRepository.findByIdAndIsDelete(id,Whether.NO);
            if (banner == null) {
                jsonResult.errorParam("加载BANNER信息失败", log);
                return;
            }
            Long mallIdDb = banner.getMallId();
            if(mallId!=mallIdDb){
                jsonResult.errorParam("没有查询权限", log);
                return;
            }
            jsonResult.data = banner;

        };
        return doing.go(request, log);

    }


    /**
     * @api {put} /mall/mobile/banner/delete/ 删除banner
     * @apiGroup mall_mobileBanner
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {String} id <code>必须参数</code> 记录id
     * @apiSuccessExample {json} Success-Response:
     * {
     *   "code": "1",
     *   "desc": "成功"
     * }
     */
    @RequestMapping(value = Routes.MALL_MOBILE_BANNER_DELETE, method = RequestMethod.PUT)
    public JsonResult deleteInfo(@RequestBody BannerDto dto, HttpServletRequest request) {
        UserInfoDto userDto = userHelper.getSession(request);
        Long mallId = userDto.mall.getId();
        RestDoing doing = jsonResult -> {
            Long id = dto.getId();
            if (null == id) {
                jsonResult.errorParam("ID不能为空", log);
                return;
            }
            Banner banner = bannerRepository.findByIdAndIsDelete(id, Whether.NO);
            if (banner == null) {
                jsonResult.errorParam("加载BANNER信息失败", log);
                return;
            }
            Long mallIdDb = banner.getMallId();
            if(mallId!=mallIdDb){
                jsonResult.errorParam("没有删除权限", log);
                return;
            }
            banner.setIsDelete(Whether.YES);
            bannerRepository.save(banner);
        };
        return doing.go(request, log);
    }


    /**
     * @api {post} /mall/mobile/banner/save 新增banner
     * @apiGroup mall_mobileBanner
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {String} picPath <code>必须参数</code> 图片地址
     * @apiParam {String} title <code>必须参数</code> 图片标题
     * @apiParam {String} url 图片链接
     * @apiSuccessExample {json} Success-Response:
     * {
     *     "code":"1",
     *     "desc":"成功",
     *     "data":{
     *         "id":10,
     *         "dateCreated":"2016-06-13 18:28:41",
     *         "lastUpdated":"2016-11-11 19:08:18",
     *         "version":1,
     *         "mallId":1,
     *         "picPath":"/20161110/2016111018013002.png",
     *         "seqNo":1,
     *         "title":"testTitle04",
     *         "url":"www.sougou.com"
     *     }
     * }
     */
    @RequestMapping(value = Routes.MALL_MOBILE_BANNER_SAVE, method = RequestMethod.POST)
    public JsonResult addInfo(@RequestBody BannerDto dto, HttpServletRequest request) {
        UserInfoDto userDto = userHelper.getSession(request);
        Long mallId = userDto.mall.getId();
        RestDoing doing = jsonResult -> {
            if (dto == null) {
                jsonResult.errorParam("BANNER信息为空", log);
                return;
            }
            if (dto.getPicPath() == null) {
                jsonResult.errorParam("图片路径为空", log);
                return;
            }
            if (dto.getTitle() == null) {
                jsonResult.errorParam("标题为空", log);
                return;
            }
            Banner banner = bannerHelper.chgCtoToDomain(dto);
            banner.setIsDelete(Whether.NO);
            banner.setMallId(mallId);
            Banner maxBanner = bannerRepository.findTop1ByIsDeleteOrderBySeqNoDesc( Whether.NO);
            Integer maxSeqno =0;
            if(null!=maxBanner){
                maxSeqno = maxBanner.getSeqNo();
            }
            Integer nextNo = maxSeqno + 1;
            banner.setSeqNo(nextNo);
            bannerRepository.save(banner);
            jsonResult.data = banner;
        };
        return doing.go(request, log);
    }


    /**
     * @api {put} /mall/mobile/banner/update 修改banner
     * @apiGroup mall_mobileBanner
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {Long} id <code>必须参数</code> 记录id
     * @apiParam {String} picPath <code>必须参数</code> 图片地址
     * @apiParam {String} title <code>必须参数</code> 图片标题
     * @apiParam {String} url <code>可选参数</code> 图片链接
     * @apiSuccessExample {json} Success-Response:
     * {
     *     "code":"1",
     *     "desc":"成功",
     *     "data":{
     *         "id":10,
     *         "dateCreated":"2016-06-13 18:28:41",
     *         "lastUpdated":"2016-11-11 19:08:18",
     *         "version":1,
     *         "mallId":1,
     *         "picPath":"/20161110/2016111018013002.png",
     *         "seqNo":1,
     *         "title":"testTitle04",
     *         "url":"www.sougou.com"
     *     }
     * }
     */
    @RequestMapping(value = Routes.MALL_MOBILE_BANNER_UPDATE, method = RequestMethod.PUT)
    public JsonResult updateInfo(@RequestBody BannerDto dto, HttpServletRequest request) {
        UserInfoDto userDto = userHelper.getSession(request);
        Long mallId = userDto.mall.getId();
        RestDoing doing = jsonResult -> {
            if (dto == null) {
                jsonResult.errorParam("BANNER信息为空", log);
                return;
            }
            Long id = dto.getId();
            if (dto.getId() == null) {
                jsonResult.errorParam("记录id为空", log);
                return;
            }
            if (dto.getPicPath() == null) {
                jsonResult.errorParam("图片地址为空", log);
                return;
            }
            if (dto.getTitle() == null) {
                jsonResult.errorParam("图片标题为空", log);
                return;
            }
            Banner banner = bannerRepository.findByIdAndIsDelete(id,Whether.NO);
            if (banner == null) {
                jsonResult.remind(Banner.REMIND_RECORD_IS_NOT_EXIST,log);;
                return;
            }
            Long mallIdDb = banner.getMallId();
            if(mallId!=mallIdDb){
                jsonResult.errorParam("没有更新权限", log);
                return;
            }
            String title = dto.getTitle();
            if (StringUtils.isNotBlank(title)) {
                banner.setTitle(title);
            }

            String picPath = dto.getPicPath();
            if (StringUtils.isNotBlank(picPath)) {
                banner.setPicPath(picPath);
            }

            String url = dto.getUrl();
            if (StringUtils.isNotBlank(url)) {
                banner.setUrl(url);
            }

            bannerRepository.save(banner);
            jsonResult.data = banner;
        };
        return doing.go(request, log);
    }


    /**
     * @api {get} /mall/mobile/banner/list 搜索banner
     * @apiGroup mall_mobileBanner
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {String} title <code>可选参数</code> 标题
     * @apiSuccessExample {json} Success-Response:
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data": [
     *      {
     *        "id": 10,
     *        "dateCreated": "2016-06-13 18:28:41",
     *        "lastUpdated": "2016-11-11 19:08:18",
     *        "version": 1,
     *        "mallId": 1,
     *        "picPath": "/20161110/2016111018013002.png",
     *        "seqNo": 1,
     *        "title": "testTitle04",
     *        "url": "www.sougou.com"
     *      }
     *   ]
     * }
     */
    @RequestMapping(value = Routes.MALL_MOBILE_BANNER_LIST, method = RequestMethod.GET)
    public JsonResult listInfo(BannerDto dto, HttpServletRequest request) {
        UserInfoDto userDto = userHelper.getSession(request);
        Long mallId = userDto.mall.getId();
        RestDoing doing = jsonResult -> {
            if (dto == null) {
                jsonResult.errorParam("BANNER信息为空", log);
                return;
            }
            String title = dto.getTitle();
            List<Banner> articles;
            if (StringUtils.isNotBlank(title)) {
                articles = bannerRepository.findByTitleLikeAndMallIdAndIsDeleteOrderBySeqNoAsc(title, mallId,Whether.NO);
            } else {
                articles = bannerRepository.findByMallIdAndIsDeleteOrderBySeqNoAsc(mallId,Whether.NO);
            }
            jsonResult.data = articles;
        };
        return doing.go(request, log);
    }


    /**
     * @api {put} /mall/mobile/banner/sort banner调整排序
     *
     * @apiGroup mall_mobileBanner
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {String=UP("前移"), DOWN("后移")} direction <code>必选参数</code> 类型
     * @apiParam {Long} id <code>必选参数</code> 记录id
     * @apiSuccessExample {json} Success-Response:
     * {
     *  "code": "1",
     *  "desc": "成功"
     * }
     */
    @RequestMapping(value = Routes.MALL_MOBILE_BANNER_SORT, method = RequestMethod.PUT)
    public JsonResult sort(@RequestBody BannerDto dto, HttpServletRequest request) {
        UserInfoDto userDto = userHelper.getSession(request);
        Long mallId = userDto.mall.getId();

        RestDoing doing = jsonResult -> {

            if (dto == null) {
                jsonResult.errorParam("BANNER信息为空", log);
                return;
            }

            Long id = dto.getId();
            if (dto.getId() == null) {
                jsonResult.errorParam("记录id为空", log);
                return;
            }

            String direction = dto.getDirection();
            if (StringUtils.isBlank(direction)) {
                jsonResult.errorParam("请添加调整顺序按钮", log);
                return;
            } else if (!direction.equals(Banner.UP) && !direction.equals(Banner.DOWN)) {
                jsonResult.errorParam("direction数据内容错误", log);
                return;
            }

            Banner banner = bannerRepository.findByIdAndIsDelete(id,Whether.NO);
            if (banner == null) {
                jsonResult.remind(Banner.REMIND_RECORD_IS_NOT_EXIST,log);;
                return;
            }

            Banner aboutBanner = bannerRepository.findBannerAbout(banner.getSeqNo(),mallId, direction);
            if(null==aboutBanner){
                jsonResult.remind("不能继续调整顺序",log);
                return;
            }
            int tem0 = aboutBanner.getSeqNo();
            int tem1 = banner.getSeqNo();
            aboutBanner.setSeqNo(tem1);
            banner.setSeqNo(tem0);

            bannerRepository.save(banner);

            bannerRepository.save(aboutBanner);
//            jsonResult.data = banner;
        };


        return doing.go(request, log);


    }

}
